<template>
  <div class="user-favorites-container">
    <div class="user-layout">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <UserSidebar />
      </div>
      
      <!-- 内容区 -->
      <div class="content">
        <div class="page-header">
          <h1>我的收藏</h1>
          <p>查看您收藏的车辆信息</p>
        </div>
        
        <el-card class="favorites-card">
          <template #header>
            <div class="favorites-card-header">
              <span>共 {{ total }} 个收藏</span>
              <div class="filter-box">
                <el-select v-model="filterType" placeholder="筛选" @change="handleFilterChange">
                  <el-option label="全部" value="all" />
                  <el-option label="价格从低到高" value="priceAsc" />
                  <el-option label="价格从高到低" value="priceDesc" />
                  <el-option label="最近收藏" value="timeDesc" />
                </el-select>
              </div>
            </div>
          </template>
          
          <!-- 收藏列表 -->
          <div class="favorites-list" v-loading="loading">
            <template v-if="favoriteList.length > 0">
              <div v-for="item in favoriteList" :key="item.id" class="favorite-item">
                <el-card shadow="hover">
                  <div class="car-info">
                    <el-image :src="item.carImage || defaultCarImage" class="car-image" fit="cover"></el-image>
                    <div class="car-details">
                      <h3 class="car-title" @click="viewCarDetail(item.carId)">
                        {{ item.carBrand }} {{ item.carModel }}
                      </h3>
                      <div class="car-specs">
                        <el-tag size="small">{{ item.carType }}</el-tag>
                        <el-tag size="small" type="info">{{ item.produceYear }}年</el-tag>
                        <el-tag size="small" type="success">{{ item.mileage }}万公里</el-tag>
                      </div>
                      <div class="car-price">
                        <span class="price">{{ item.price }}万</span>
                        <span class="origin-price" v-if="item.originPrice">原价{{ item.originPrice }}万</span>
                      </div>
                      <div class="car-tags">
                        <el-tag size="small" type="danger" v-if="item.isHot">热门</el-tag>
                        <el-tag size="small" type="warning" v-if="item.isRecommend">推荐</el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="favorite-actions">
                    <span class="favorite-time">收藏于 {{ formatDate(item.createTime) }}</span>
                    <div class="action-buttons">
                      <el-button type="primary" size="small" @click="viewCarDetail(item.carId)">查看详情</el-button>
                      <el-button type="danger" size="small" @click="removeFavorite(item.id)">取消收藏</el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </template>
            
            <!-- 空状态 -->
            <el-empty v-else description="暂无收藏数据">
              <template #description>
                <p>还没有收藏车辆，快去浏览感兴趣的车吧！</p>
              </template>
              <el-button type="primary" @click="goCars">去浏览车辆</el-button>
            </el-empty>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[8, 12, 24, 36]"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserSidebar from '../components/UserSidebar.vue'

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const filterType = ref('all')
const defaultCarImage = '/car-default.jpg'

// 收藏列表数据
const favoriteList = ref([
  // 模拟数据，实际应从API获取
  {
    id: 1,
    carId: 101,
    carBrand: '奔驰',
    carModel: 'C级 2023款',
    carType: '轿车',
    produceYear: 2023,
    mileage: 0.5,
    price: 32.98,
    originPrice: 35.99,
    carImage: 'https://via.placeholder.com/300x200',
    isHot: true,
    isRecommend: true,
    createTime: '2023-04-15 10:30:15'
  },
  {
    id: 2,
    carId: 102,
    carBrand: '宝马',
    carModel: '3系 2022款',
    carType: '轿车',
    produceYear: 2022,
    mileage: 1.2,
    price: 29.8,
    originPrice: null,
    carImage: 'https://via.placeholder.com/300x200',
    isHot: false,
    isRecommend: true,
    createTime: '2023-04-18 15:42:36'
  },
  {
    id: 3,
    carId: 103,
    carBrand: '奥迪',
    carModel: 'Q5 2022款',
    carType: 'SUV',
    produceYear: 2022,
    mileage: 0.8,
    price: 36.5,
    originPrice: 39.8,
    carImage: 'https://via.placeholder.com/300x200',
    isHot: true,
    isRecommend: false,
    createTime: '2023-04-20 09:15:42'
  },
  {
    id: 4,
    carId: 104,
    carBrand: '特斯拉',
    carModel: 'Model 3',
    carType: '新能源',
    produceYear: 2023,
    mileage: 0.3,
    price: 27.9,
    originPrice: null,
    carImage: 'https://via.placeholder.com/300x200',
    isHot: true,
    isRecommend: true,
    createTime: '2023-04-21 12:25:33'
  }
])

// 时间格式化
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  
  const date = new Date(dateStr.replace(' ', 'T'))
  const now = new Date()
  const diff = now - date
  
  // 一天内显示几小时前
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return hours > 0 ? `${hours}小时前` : '刚刚'
  }
  
  // 一周内显示几天前
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  
  // 其他显示具体日期
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 查看车辆详情
const viewCarDetail = (carId) => {
  router.push(`/car/${carId}`)
}

// 取消收藏
const removeFavorite = (favoriteId) => {
  ElMessageBox.confirm('确定要取消收藏该车辆吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用取消收藏接口
    loading.value = true
    setTimeout(() => {
      // 模拟API调用
      favoriteList.value = favoriteList.value.filter(item => item.id !== favoriteId)
      total.value -= 1
      ElMessage.success('已取消收藏')
      loading.value = false
    }, 500)
  }).catch(() => {
    // 用户取消操作
  })
}

// 前往车辆列表页
const goCars = () => {
  router.push('/cars')
}

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchFavorites()
}

// 改变每页条数
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFavorites()
}

// 改变页码
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFavorites()
}

// 获取收藏列表
const fetchFavorites = () => {
  loading.value = true
  
  // 这里应该调用实际的API接口获取收藏数据
  // 以下是模拟数据处理
  setTimeout(() => {
    // 模拟排序
    let sortedList = [...favoriteList.value]
    
    switch (filterType.value) {
      case 'priceAsc':
        sortedList.sort((a, b) => a.price - b.price)
        break
      case 'priceDesc':
        sortedList.sort((a, b) => b.price - a.price)
        break
      case 'timeDesc':
        sortedList.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        break
      default:
        // 默认不排序
        break
    }
    
    // 更新总数
    total.value = sortedList.length
    
    // 模拟分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    favoriteList.value = sortedList.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  fetchFavorites()
})
</script>

<style lang="scss" scoped>
.user-favorites-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .user-layout {
    display: flex;
    gap: 20px;
    
    .sidebar {
      width: 250px;
      flex-shrink: 0;
    }
    
    .content {
      flex: 1;
      
      .page-header {
        margin-bottom: 20px;
        
        h1 {
          font-size: 24px;
          color: #333;
          margin-bottom: 8px;
        }
        
        p {
          color: #666;
          font-size: 14px;
          margin: 0;
        }
      }
    }
  }
  
  .favorites-card {
    margin-bottom: 20px;
    
    .favorites-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-size: 14px;
        color: #666;
      }
      
      .filter-box {
        width: 180px;
      }
    }
  }
  
  .favorites-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
    
    .favorite-item {
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .el-card {
        height: 100%;
        display: flex;
        flex-direction: column;
      }
      
      .car-info {
        margin-bottom: 15px;
        
        .car-image {
          width: 100%;
          height: 180px;
          border-radius: 4px;
          margin-bottom: 10px;
        }
        
        .car-details {
          .car-title {
            font-size: 16px;
            color: #333;
            margin: 0 0 8px 0;
            cursor: pointer;
            
            &:hover {
              color: #409EFF;
            }
          }
          
          .car-specs {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
          }
          
          .car-price {
            margin-bottom: 8px;
            
            .price {
              font-size: 18px;
              color: #f56c6c;
              font-weight: bold;
              margin-right: 8px;
            }
            
            .origin-price {
              font-size: 14px;
              color: #999;
              text-decoration: line-through;
            }
          }
          
          .car-tags {
            display: flex;
            gap: 8px;
          }
        }
      }
      
      .favorite-actions {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .favorite-time {
          font-size: 12px;
          color: #999;
          margin-bottom: 10px;
        }
        
        .action-buttons {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .user-favorites-container {
    .user-layout {
      flex-direction: column;
      
      .sidebar {
        width: 100%;
      }
    }
    
    .favorites-list {
      grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
    }
  }
}
</style> 